<template>
  <div class="bg-[white] w-full h-full pt-[40px] px-[40px] text-base flex flex-col">
    <!-- 搜索区域 -->
    <div class="flex justify-start items-center">
      <InputText type="text" label="仓库名称" placeholder="请输入仓库名称" class="w-[290px] mr-[20px]" v-model="searchInfo.name" />
      <Button type="primary" content="查询" class="mr-[20px]" @click="getData">
        <template #icon>
          <IconSvg name="search" class="w-[18px] h-[18px]"></IconSvg>
        </template>
      </Button>
      <Button content="重置" class="mr-[20px]" @click="resetSearch">
        <template #icon>
          <IconSvg name="refresh" class="w-[15px] h-[15px]"></IconSvg>
        </template>
      </Button>
    </div>

    <!-- 表格区域 -->
    <div class="mt-[40px] flex-1 overflow-auto">
      <div class="flex justify-start items-center">
        <Button type="primary" content="新增" class="mr-[20px]" @click="openAddModel">
          <template #icon>
            <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
          </template>
        </Button>
      </div>

      <DataTable :dataSource="tableData" :columns="tableColumns" class="mt-[20px]">
        <!-- 操作列模板 - 新增修改按钮 -->
        <template #action="{ item }">
          <a @click="openLocationModel(item)" class="ml-2 text-blue-500 cursor-pointer">仓位设置</a>
          <a @click="openEditModel(item)" class="ml-2 text-blue-500 cursor-pointer">修改</a>
          <a @click="handleWarehouseDelete(item)" class="ml-2 text-red-500 cursor-pointer">删除</a>
        </template>
      </DataTable>
    </div>

    <!-- 仓库分页区域 -->
    <div class="flex justify-end items-center my-4">
      <label class="font-medium">共{{ warehousePageData.total }}条</label>
      <PaginationBasic :total="warehousePageData.total" :page-size="warehousePageData.pageSize"
        v-model:current="warehousePageData.currentPage" @onPageChange="handleWarehousePageChange" />
    </div>


    <!-- 新增/修改仓库模态框 - 修改为通用模态框 -->
    <Model :show="showAddModel" @close="handleCancel">
      <template #header>
        <h3>{{ isAdd ? '添加仓库' : '修改仓库' }}</h3>
      </template>
      <template #body>
        <div class="flex flex-col gap-[15px]">
          <InputText type="text" label="名称" placeholder="请输入名称" class="w-[360px]" v-model="addInfo.warehousename"
            label-width="60px" />

          <!-- 只有新增时显示以下字段 -->
          <template v-if="isAdd">
            <InputSelect label="品类型号" label-width="60px" class="w-[360px] mr-[20px]"
              v-model="addInfo.useidentificationid">
              <option v-for="item in useidentificationid" :key="item.value" :value="item.value">
                {{ item.label }}
              </option>
            </InputSelect>
            <InputSelect label="赋码规则" label-width="60px" class="w-[360px] mr-[20px]" v-model="addInfo.useruleid">
              <option v-for="item in useruleid" :key="item.value" :value="item.value">
                {{ item.label }}
              </option>
            </InputSelect>
          </template>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="handleCancel"></Button>
          <Button type="primary" content="确定" @click="handleConfirm"></Button>
        </div>
      </template>
    </Model>

    <!-- 仓库位置设置模态框 -->
    <Model :show="showLocationModel" @close="showLocationModel = false">
      <template #header>
        <h3>仓位设置</h3>
      </template>

      <template #body>
        <!-- 新增仓位按钮 -->
        <div class="flex justify-start items-center mb-[10px]">
          <Button type="primary" content="新增仓位" @click="openAddLocation">
            <template #icon>
              <IconSvg name="add" class="w-[18px] h-[18px]"></IconSvg>
            </template>
          </Button>
        </div>

        <DataTable :dataSource="tableData2" :columns="tableColumns2" class="mt-[20px]">
          <template #action="{ item }">
            <a @click="handleLocationBind(item)" class="ml-2 text-blue-500 cursor-pointer">绑定设备</a>
            <a @click="editLocation(item)" class="ml-2 text-blue-500 cursor-pointer">修改</a>
            <a @click="handleLocationDelete(item)" class="ml-2 text-red-500 cursor-pointer">删除</a>
          </template>
        </DataTable>
        <div class="flex justify-end items-center my-4">
          <label class="font-medium">共{{ locationPageData.total }}条</label>
          <PaginationBasic :total="locationPageData.total" :page-size="locationPageData.pageSize"
            v-model:current="locationPageData.currentPage" @onPageChange="handleLocationPageChange" />
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="showLocationModel = false"></Button>
          <Button type="primary" content="保存" @click="saveLocation"></Button>
        </div>
      </template>
    </Model>

    <!-- 设备绑定弹窗 -->
    <Model :show="showBindDeviceModel" @close="handleBindDeviceCancel" :key="showBindDeviceModel">
      <template #header>
        <h3>绑定设备</h3>
      </template>
      <template #body>
        <div class="flex flex-col gap-[15px]">
          <InputSelect label="冲压件设备" label-width="60px" class="w-[360px]" v-model="stampingpartid">

            <option v-for="device in stampingpart" :key="device.id" :value="device.id">
              {{ device.devicename }}
            </option>
          </InputSelect>
          <InputSelect label="模具设备" label-width="60px" class="w-[360px]" v-model="moldid">

            <option v-for="device in mold" :key="device.id" :value="device.id">
              {{ device.devicename }}
            </option>
          </InputSelect>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="handleBindDeviceCancel"></Button>
          <Button type="primary" content="确定" @click="confirmBindDevice"></Button>
        </div>
      </template>
    </Model>

    <!-- 在仓位设置模态框之后添加新增仓位模态框 -->
    <Model :show="showAddLocationModel" @close="handleLocationCancel">
      <template #header>
        <h3>{{ isEditLocation ? '修改仓位' : '新增仓位' }}</h3>
      </template>
      <template #body>
        <div class="flex flex-col gap-[15px]">
          <!-- 名称字段：始终显示 -->
          <InputText type="text" label="仓位名称" placeholder="请输入仓位名称" class="w-[360px]"
            v-model="locationForm.positionname" label-width="60px" />

          <!-- 品类型号和赋码规则：仅新增时显示，修改时隐藏 -->
          <InputSelect v-if="!isEditLocation" label="品类型号" label-width="60px" class="w-[360px] mr-[20px]"
            v-model="locationForm.useidentificationid">
            <option v-for="item in useidentificationid" :key="item.value" :value="item.value">
              {{ item.label }}
            </option>
          </InputSelect>

          <InputSelect v-if="!isEditLocation" label="赋码规则" label-width="60px" class="w-[360px] mr-[20px]"
            v-model="locationForm.useruleid">
            <option v-for="item in useruleid" :key="item.value" :value="item.value">
              {{ item.label }}
            </option>
          </InputSelect>
        </div>
      </template>
      <template #footer>
        <div class="flex justify-around">
          <Button content="取消" @click="handleLocationCancel"></Button>
          <Button type="primary" content="确定" @click="confirmLocation"></Button>
        </div>
      </template>
    </Model>
  </div>
</template>
<script setup>
import InputText from "../../components/InputText.vue";
import InputSelect from "../../components/InputSelect.vue";
import Button from "../../components/Button.vue";
import IconSvg from "../../components/IconSvg.vue";
import DataTable from "../../components/DataTable.vue";
import Model from "../../components/Model.vue";
import PaginationBasic from "../../components/PaginationBasic.vue";
import Message from "../../components/Message/Message.js";
import { ref, onMounted } from "vue"
import axios from "../../axios/axios.js";


// 新增仓位相关状态
const showAddLocationModel = ref(false);
const locationForm = ref({});
const isEditLocation = ref(false);
const currentLocation = ref(null);

// 设备绑定相关状态
const showBindDeviceModel = ref(false); // 绑定设备弹窗显示状态
const currentLocationItem = ref(null); // 当前操作的仓位项
const stampingpart = ref([]);
const mold = ref([]);
const stampingpartid = ref(''); // 选中的设备ID
const moldid = ref(''); // 选中的设备ID



// 打开新增仓位弹窗
const openAddLocation = () => {
  // 隐藏仓位设置模态框
  showLocationModel.value = false;
  isEditLocation.value = false;
  locationForm.value = {
    positionname: '',
    useidentificationid: '',
    useruleid: '',
    warehouseId: operateItem.value?.id
  };
  axios.get("/api/identify/selectall").then(res => {
    if (res.data.Code === "200") {
      useidentificationid.value = res.data.Data.map(item => ({
        value: item.id,
        label: item.name,
      }));
    }
  });
  axios.get("/api/codingrule/selectall").then(res => {
    if (res.data.Code === "200") {
      useruleid.value = res.data.Data.map(item => ({
        value: item.id,
        label: item.name,
      }));
    }
  });
  // 显示新增仓位模态框
  showAddLocationModel.value = true;
};

// 新增/修改仓位的确认方法
const confirmLocation = () => {
  // 验证表单
  if (!locationForm.value.positionname?.trim()) {
    Message.warn('请输入仓位名称');
    return;
  }
  // 构建提交数据
  const submitData = {
    ...locationForm.value,
    warehouseId: operateItem.value?.id
  };

  // 如果是修改操作，仅保留名称和ID字段（移除其他字段）
  if (isEditLocation.value) {
    submitData.id = currentLocation.value.id; // 必须传递ID用于修改
    submitData.warehouseId = operateItem.value?.id;
    // 删除非名称字段，确保仅修改名称
    delete submitData.useidentificationid;
    delete submitData.useruleid;
  }
  // 区分新增和修改
  const apiUrl = isEditLocation.value
    ? `/api/position/update?id=${currentLocation.value.id}`
    : `/api/position/save?warehouseId=${operateItem.value?.id}`;

  axios.post(apiUrl, submitData)
    .then(res => {
      if (res.data.Code === "200") {
        Message.success(isEditLocation.value ? '仓位修改成功' : '仓位添加成功');
        // 隐藏新增/修改仓位模态框
        showAddLocationModel.value = false;
        // 重新显示仓位设置模态框
        showLocationModel.value = true;
        // 重新加载仓位数据
        getLocationData(); // 需要实现此方法加载仓位列表
      } else {
        Message.warn(res.data.Msg || (isEditLocation.value ? '修改失败' : '添加失败'));
      }
    })
    .catch(err => {
      Message.error('操作失败，请重试');
      console.error('仓位操作错误：', err);
    });
};

// 仓位操作的取消方法
const handleLocationCancel = () => {
  showAddLocationModel.value = false;
  // 重新显示仓位设置模态框
  showLocationModel.value = true;
  locationForm.value = {};
  currentLocation.value = null;
};

// 添加加载仓位数据的方法
const getLocationData = () => {
  if (!operateItem.value?.id) return;

  const url = `/api/position/select?warehouseId=${operateItem.value.id}&pageIndex=${locationPageData.value.currentPage}&pageSize=${locationPageData.value.pageSize}`;

  axios.get(url)
    .then(res => {
      if (res.data.Code === "200") {
        // 正确：提取 records 数组作为表格数据源
        tableData2.value = res.data.Data?.records || [];
        locationPageData.value = {
          ...locationPageData.value,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        };
      } else {
        Message.warn(res.data.Msg || '加载仓位数据失败');
        tableData2.value = []; // 错误时也确保是数组
      }
    })
    .catch(err => {
      console.error('加载仓位数据错误：', err);
      Message.error('加载仓位数据失败');
      tableData2.value = []; // 异常时也确保是数组
    });
};


// 打开修改仓位弹窗
const editLocation = (item) => {
  isEditLocation.value = true;
  currentLocation.value = item;
  // 仅初始化名称字段（其他字段不传递或置空）
  locationForm.value = {
    positionname: item.positionname, // 只保留名称字段
    // 移除其他字段（如useidentificationid、useruleid等），避免修改
  };
  showAddLocationModel.value = true;
};
// 搜索信息
const searchInfo = ref({ name: '', categoryName: '' });

// 模态框状态
const showAddModel = ref(false);
const showLocationModel = ref(false); // 仓库位置模态框

// 表单数据
const addInfo = ref({});
const operateItem = ref(null);
const isAdd = ref(false);

// 仓库分页数据
const warehousePageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
});

// 仓位分页数据
const locationPageData = ref({
  currentPage: 1,
  total: 0,
  pageSize: 10,
});

// 仓库类型数据
const useidentificationid = ref([])
const useruleid = ref([])
// 表格数据和列配置
const tableData = ref([]);
const tableColumns = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'warehousename', title: '仓库名称', dataIndex: 'warehousename', width: 100 },
  { key: 'useidentificationname', title: '使用标识', dataIndex: 'useidentificationname', width: 100 },
  { key: 'identification', title: '标识', dataIndex: 'identification' },
  { key: 'createtime', title: '创建时间', dataIndex: 'createtime' },
  { key: 'action', title: '操作', dataIndex: 'action' },
]);
const tableData2 = ref([]);
const tableColumns2 = ref([
  { key: 'id', title: '编号', dataIndex: 'id', width: 60 },
  { key: 'positionname', title: '仓位名称', dataIndex: 'positionname', width: 100 },
  { key: 'useidentificationname', title: '使用标识', dataIndex: 'useidentificationname', width: 100 },
  { key: 'identificationcode', title: '标识', dataIndex: 'identificationcode' },
  { key: 'createtime', title: '创建时间', dataIndex: 'createtime' },
  { key: 'action', title: '操作', dataIndex: 'action' },
]);

// 分页变化处理
const handleWarehousePageChange = (page) => {
  warehousePageData.value.currentPage = page;
  getData();
};

const handleLocationPageChange = (page) => {
  locationPageData.value.currentPage = page;
  getLocationData();
};


// 打开位置设置模态框
const openLocationModel = (item) => {
  operateItem.value = item;
  showLocationModel.value = true;
  getLocationData();
};

// 打开修改模态框
const openEditModel = (item) => {
  isAdd.value = false;
  operateItem.value = item;
  showAddModel.value = true;
  // 仅初始化名称字段（符合只能修改名字的需求）
  addInfo.value = {
    warehousename: item.name
  };
};

// 获取设备列表（区分冲压件和模具）
const getDeviceList = () => {
  // 加载冲压件设备
  axios.get('/api/codingdevice/selectall?type=冲压件')
    .then(res => {
      if (res.data.Code === "200") {
        stampingpart.value = res.data.Data.map(item => ({
          id: item.id,
          devicename: item.devicename
        }));
      } else {
        Message.warn(res.data.Msg || '获取冲压件设备失败');
      }
    })

  // 加载模具设备
  axios.get('/api/codingdevice/selectall?type=模具')
    .then(res => {
      if (res.data.Code === "200") {
        mold.value = res.data.Data.map(item => ({
          id: item.id,
          devicename: item.devicename
        }));
      } else {
        Message.warn(res.data.Msg || '获取模具设备失败');
      }
    })
};


// 打开绑定设备弹窗
const handleLocationBind = (item) => {
  currentLocationItem.value = item;

  showBindDeviceModel.value = true;
  // 确保设备列表已加载
  if (stampingpart.value.length === 0 || mold.value.length === 0) {
    getDeviceList();
  }
};

// 取消绑定设备
const handleBindDeviceCancel = () => {
  showBindDeviceModel.value = false;
  setTimeout(() => {
    currentLocationItem.value = null;
  }, 300);
};

// 确认绑定设备
const confirmBindDevice = () => {

  if (!currentLocationItem.value) {
    Message.warn('未选择仓位');
    return;
  }

  // 调用绑定接口
  axios.post("/api/position/binddevice", {
    id: currentLocationItem.value.id,
    stampingpartid: stampingpartid.value,
    moldid: moldid.value,
  })
    .then(res => {
      if (res.data.Code === "200") {
        Message.success('设备绑定成功');
        handleBindDeviceCancel();

      }
    })
};

// 删除
const handleWarehouseDelete = (item) => {
  if (window.confirm(`确定要删除仓库"${item.name}"吗？此操作不可撤销！`)) {
    axios.get(`/api/warehouse/delete?id=${item.id}`)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('仓库删除成功');
          getData();
        } else {
          Message.warn(res.data.Msg || '删除失败');
        }
      })
      .catch(err => {
        Message.error('删除失败，请重试');
        console.error('仓库删除错误：', err);
      });
  }
};

const handleLocationDelete = (item) => {
  if (window.confirm(`确定要删除仓位"${item.positionname}"吗？此操作不可撤销！`)) {
    axios.get(`/api/position/delete?id=${item.id}`)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('仓位删除成功');
          getLocationData();
        } else {
          Message.warn(res.data.Msg || '删除失败');
        }
      })
      .catch(err => {
        Message.error('删除失败，请重试');
        console.error('仓位删除错误：', err);
      });
  }
};



// 确认提交（新增/修改）
const handleConfirm = () => {
  // 验证名称必填
  if (!addInfo.value.warehousename?.trim()) {
    Message.warn('请输入仓库名称');
    return;
  }

  if (isAdd.value) {
    // 新增逻辑
    const submitData = {
      "warehousename": addInfo.value.warehousename,
      "useidentificationid": addInfo.value.useidentificationid,
      "useruleid": addInfo.value.useruleid,
    };
    axios.post('/api/warehouse/save', submitData)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('仓库添加成功');
          showAddModel.value = false;
          addInfo.value = {};
          getData();
        } else {
          Message.warn(res.data.Msg || '添加失败');
        }
      })
      .catch(err => {
        Message.error('添加失败，请重试');
        console.error('仓库新增错误：', err);
      });
  } else {
    // 修改逻辑（仅提交名称）
    const submitData = {
      "id": operateItem.value.id,
      "warehousename": addInfo.value.warehousename
    };
    axios.post('/api/warehouse/update', submitData)
      .then(res => {
        if (res.data.Code === "200") {
          Message.success('仓库修改成功');
          showAddModel.value = false;
          addInfo.value = {};
          operateItem.value = null;
          getData();
        } else {
          Message.warn(res.data.Msg || '修改失败');
        }
      })
      .catch(err => {
        Message.error('修改失败，请重试');
        console.error('仓库修改错误：', err);
      });
  }
};

const handleCancel = () => {
  isAdd.value = false;
  addInfo.value = {};
  operateItem.value = null;
  showAddModel.value = false;
};

const resetSearch = () => {
  searchInfo.value = { name: '' };
  getData();
};

// 保存位置设置（补充空实现避免报错）
const saveLocation = () => {
  // 实现保存逻辑
  showLocationModel.value = false;
  Message.success('位置设置已保存');
};

// 获取仓库列表
const getData = () => {
  let url = `/api/warehouse/select?pageIndex=${warehousePageData.value.currentPage}&pageSize=${warehousePageData.value.pageSize}`;
  if (searchInfo.value.name.trim()) {
    url += `&name=${encodeURIComponent(searchInfo.value.name.trim())}`;
  }

  axios.get(url)
    .then(res => {
      if (res.data.Code === "200") {
        tableData.value = res.data.Data.records || [];
        warehousePageData.value = {
          ...warehousePageData.value,
          total: res.data.Data.total || 0,
          pageSize: res.data.Data.size || 10,
        };
      } else {
        Message.warn(res.data.Msg || '获取仓库列表失败');
        tableData.value = [];
        warehousePageData.value.total = 0;
      }
    })
    .catch(err => {
      Message.error('网络错误，无法获取仓库列表');
      console.error('仓库列表请求失败：', err);
    });
};




// 打开新增模态框
const openAddModel = () => {
  isAdd.value = true;
  showAddModel.value = true;
  addInfo.value = {};

  axios.get("/api/identify/selectall").then(res => {
    if (res.data.Code === "200") {
      useidentificationid.value = res.data.Data.map(item => ({
        value: item.id,
        label: item.name,
      }));
    }
  });
  axios.get("/api/codingrule/selectall").then(res => {
    if (res.data.Code === "200") {
      useruleid.value = res.data.Data.map(item => ({
        value: item.id,
        label: item.name,
      }));
    }
  });
};

onMounted(() => {
  getData();
});
</script>
<style scoped></style>